package com.xyc.petmallsystem.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author Joel
 * @date 2021/12/3
 */

@Component
public class RedisUtils {
    @Autowired
    private RedisTemplate redisTemplate;

    //指定缓存的失效时间
    public boolean setExpire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS); // 秒数
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //获取过期时间    不存在返回 -2    存在返回-1
    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    //判断 key是否存在
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //删除key
    public void del(String key) {
        redisTemplate.delete(key);
    }

    // 添加
    public void set(Object key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    //查找名为key
    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }
}
